package com.cxs.componentcode.provider;

import com.cxs.componentcode.ResourceTable;
import com.cxs.componentcode.data.NewsInfo;
import ohos.agp.components.*;
import ohos.app.Context;

import java.util.List;
import java.util.Optional;

public class NewsListProvider extends BaseItemProvider {
    private List<NewsInfo> newsInfoList;
    private Context context;

    public NewsListProvider(List<NewsInfo> newsInfoList, Context context) {
        this.newsInfoList = newsInfoList;
        this.context = context;
    }

    @Override
    public int getCount() {
        return newsInfoList == null ? 0 : newsInfoList.size();
    }

    @Override
    public Object getItem(int i) {
        return Optional.of(newsInfoList.get(i));
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        ViewHolder viewHolder = null;
        Component cpt = component;
        if (cpt == null) {
            cpt = LayoutScatter.getInstance(context)
                    .parse(ResourceTable.Layout_item_news_layout, null, false);
            viewHolder = new ViewHolder();
            Component infoText = cpt.findComponentById(ResourceTable.Id_item_news_title);
            Component image = cpt.findComponentById(ResourceTable.Id_items_news_image);
            if (infoText instanceof Text) {
                viewHolder.infoText = (Text)infoText;
            }
            if (image instanceof Image) {
                viewHolder.image = (Image)image;
            }
            cpt.setTag(viewHolder);
        } else {
            if (cpt.getTag() instanceof ViewHolder) {
                viewHolder = (ViewHolder) cpt.getTag();
            }
        }
        if (viewHolder != null) {
            viewHolder.infoText.setText(newsInfoList.get(i).getTitle());
            viewHolder.image.setScaleMode(Image.ScaleMode.STRETCH);
        }
        return cpt;
    }

    private static class ViewHolder {
        Text infoText;
        Image image;
    }
}
